最高のNotificationにしような
概要
Mac OS Xで使用できるNotificationの話で。
Notification
に、ボタンをつけたくなったんだけどどうやんねやろ? ってなったのとちょっとハマったので備忘録。
Yosemiteで動くかどうかは明日試す。
Notificationにボタンをつけてテストの再実行
JenkinsとかCircleCIとかでテストを実行していて、特定のテストだけ、今ちょっと実行してみたいな、みたいな
そんな時がある。
で、まあ、どこかのテストの失敗時にこんなのが出るとするじゃない。
ボタンをつけて実行、とかやると、後からでも特定の失敗したテストだけ好きなときに実行できて便利、みたいな。
MacアプリなのでSwiftで書いてもよかったんだけどちょっと古いMacもあるんでObj-Cで。
標準的なボタン無しのNotification
に、任意の文字表示でボタンをつける(閉じるボタンも着く)
っていう奴を書く。
基本的なNotificationをObj-Cから出すコード
まずボタン無しを出すコードの全体が下記。
NSUserNotificationCenter *notifier;
// どこか初期化ブロック
{
notifier = [NSUserNotificationCenter defaultUserNotificationCenter];
notifier.delegate = self;
}
/**
通知
*/
- (void) notifyToUserWithStatus:(int)status withTitle:(NSString *)title message:(NSString *)message {
NSUserNotification * newUserNotification = [NSUserNotification new];
newUserNotification.title = @"title";
newUserNotification.subtitle = @"subtitle";
newUserNotification.informativeText = @"message";
[notifier deliverNotification:newUserNotification];
}
/*
Macの通知センターのデリゲート
*/
/**
notificationがタッチされた場合の挙動
*/
- (void)userNotificationCenter:(NSUserNotificationCenter *)center didActivateNotification:(NSUserNotification *)notification {
// do something
}
/**
アプリケーション側がdaemonとかUIを持たないアプリケーションでも、とにかくNotificationを表示するかどうか
*/
- (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center shouldPresentNotification:(NSUserNotification *)notification {
return true;
}
notifyToUserWithStatus:withTitle:message: メソッドにいろいろ叩き込むと、
ボタン無しで指定した文字要素でNotificationが出る。
ボタン付き
notifyToUserWithStatus:withTitle:message: メソッドの中身を下記のように変える。
- (void) notifyToUserWithStatus:(int)status withTitle:(NSString *)title message:(NSString *)message {
NSUserNotification * newUserNotification = [NSUserNotification new];
newUserNotification.title = @"title";
newUserNotification.actionButtonTitle = @"button";
newUserNotification.hasActionButton = YES;
newUserNotification.subtitle = @"subtitle";
newUserNotification.informativeText = @"message";
[notifier deliverNotification:newUserNotification];
}
はいはい簡単簡単、って思ったら、実際出ない。
で、
Info.plist に下記プロパティを付け加えると出るようになった。
key:
NSUserNotificationAlertStyle
value:
banner or alert or none
参考、Appleの死霊
こんな感じ。
まんまNSUser.. みたいなキーで通った。
コード + 上記plistの設定で、ボタンがついたりつかなかったりそも表示されなくなったりする。
banner = ボタン無し
alert = ボタンあり
none = 出なくなる
下は alert + コード側でボタンの文字をセットしたもの。
newUserNotification.actionButtonTitle = @"button";
でオリジナルのボタンのタイトルを設定しているが、このコードが無かった場合、以下みたいな表示になる。
で、ボタンが押されたイベント自体は、以下メソッドで取得できる。
userNotificationCenter:didActivateNotification:
ただ、Notificationの内容は、Userが設定.appとかから変更できる
参考:https://github.com/Daij-Djan/DDMountainNotifier/issues/3
ので、こうセットしたからといって完全にボタンが出せるわけでもない。
以上だが
2点問題があって、
1.一度キーを付け加えたらたとえキーを消しても最後にセットしてあった要素が効き続ける
例えばvalueを alert にして、保存、一度実行→キーごと行を消して再度実行、
ってやっても、Notificationからボタンが消えない。
これバグなんじゃねーかな。
2.ボタン付けたら消えなくなった
自動的に消えないので、ずっと画面上に表示されちゃう。
全然お手軽なUIじゃなかった。
信じてたのに!! スワイプでも消せないし。
というわけでお蔵入りした。